<?php

App::uses('AdminAppController', 'Admin.Controller');

/**
 * Spots Controller
 *
 * @property Spot $Spot
 */
class SpotsController extends AdminAppController {
	
	public $uses = array('Spot');
	
	public function beforeFilter() {
		parent::beforeFilter();
		$this->picturesPath = WWW_ROOT . "files" . DS . "spots";
	}
	
	public function index() {
		
		$options = array(
			'order' => 'Spot.id DESC'
		);
		
		$input = '';
		
		if( isset($this->request->query['q']) && !empty($this->request->query['q']) ) {
			App::uses('Sanitize', 'Utility');
			$input = $this->request->query['q'];
			$q = Sanitize::escape($input);
			$options['conditions'] = array( 
				"MATCH(Spot.name, Spot.address) AGAINST('$q' IN BOOLEAN MODE)" 
			);
		}
		
		$this->Spot->recursive = 0;
		
		$this->paginate = $options;
		
		$this->set('spots', $this->paginate());
		
		$this->set('q', $input);
	}
	
	public function view($id) {
		$this->Spot->id = $id;
		if (!$this->Spot->exists()) {
			$this->setUserInfo(__("Invalid Spot."), "error");
			$this->redirect( $this->referer() );
		}
		$this->set('spot', $this->Spot->read(null, $id));
	}
	
	public function add() {
		
		if ($this->request->is('post')) {
			try {
				$file = $this->request->data['Spot']['picture'];
				unset($this->request->data['Spot']['picture']);
				
				// begin transaction
				$this->Spot->getDataSource()->begin();
				$this->Spot->create();
				if( $this->Spot->saveAssociated( $this->request->data ) ) {
					if( $file['size'] > 0 && !$file['error'] ) {
						$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
						$fileName = "spot_" . $this->Spot->id . "." . $ext;
						$this->request->data['Spot']['picture'] = $fileName;
						$this->Upload->allowed_types('image/jpeg', 'image/png', 'image/gif');
						$this->Upload->custom_name($fileName);
						$this->Upload->upload($file, $this->picturesPath);
						$this->Spot->set('picture', $fileName);
						$this->Spot->set('picture_url', Router::url("/files/spots/" . $fileName));
						$this->Spot->save();
					}
					else {
						// use default picture
						$fileName = 'default_spot.png';
						$this->Spot->set('picture', $fileName);
						$this->Spot->set('picture_url', Router::url("/images/" . $fileName));
						$this->Spot->save();
					}
					$this->setUserInfo( __("Spot created."), "success" );
					// commit transaction
					$this->Spot->getDataSource()->commit();
					$this->redirect(array('action' => 'view', $this->Spot->id));
				}
				else {
					throw new Exception( __("A database error occured.") );
				}
			}
			catch(Exception $ex) {
				// rollback transaction
				$this->Spot->getDataSource()->rollback();
				// handle the exception
				$this->log("Error saving Spot: " . $ex->getMessage());
				$this->setUserInfo( __("The Spot could not be saved: ") . $ex->getMessage(), 'error');
			}
		}
		
		// view data
		$cities = $this->Spot->City->find('list', array('order' => 'City.name ASC'));
		$categories = $this->Spot->Category->find('list', array('order' => 'Category.name ASC'));
		$this->set(compact('cities', 'categories'));
	}
	
	public function edit($id = null) {
		
		$this->Spot->id = $id;
		if (!$this->Spot->exists()) {
			$this->setUserInfo(__("Invalid Spot."), "error");
			$this->redirect( $this->referer() );
		}
		
		if ($this->request->is('post') || $this->request->is('put')) {
			try {
				$file = $this->request->data['Spot']['picture'];
				unset($this->request->data['Spot']['picture']);
				
				// begin transaction
				$this->Spot->getDataSource()->begin();
				if( $this->Spot->saveAssociated( $this->request->data ) ) {
					if( $file['size'] > 0 && !$file['error'] ) {
						$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
						$fileName = "spot_" . $this->Spot->id . "." . $ext;
						$this->request->data['Spot']['picture'] = $fileName;
						$this->Upload->allowed_types('image/jpeg', 'image/png', 'image/gif');
						$this->Upload->custom_name($fileName);
						$this->Upload->upload($file, $this->picturesPath);
						$this->Spot->set('picture', $fileName);
						$this->Spot->set('picture_url', Router::url("/files/spots/" . $fileName));
						$this->Spot->save();
					}
					$this->setUserInfo( __("Spot updated."), "success" );
					// commit transaction
					$this->Spot->getDataSource()->commit();
					$this->redirect(array('action' => 'view', $this->Spot->id));
				}
				else {
					throw new Exception( __("A database error occured.") );
				}
			}
			catch(Exception $ex) {
				// rollback transaction
				$this->Spot->getDataSource()->rollback();
				// handle the exception
				$this->log("Error saving Spot: " . $ex->getMessage());
				$this->setUserInfo( __("The Spot could not be saved: ") . $ex->getMessage(), 'error');
			}
		}
		else {
			$this->request->data = $this->Spot->read(null, $id);
		}
		
		// view data
		$cities = $this->Spot->City->find('list');
		$categories = $this->Spot->Category->find('list');
		//$tags = $this->Spot->Tag->find('list');
		$this->set(compact('cities', 'categories'));
	}
	
	public function delete($id) {
		
		$this->Spot->id = $id;
		
		if (!$this->Spot->exists()) {
			$this->setUserInfo(__("Invalid spot."), "error");
			$this->redirect( $this->referer() );
		}
		
		$spot = $this->Spot->read();
		
		if ($this->Spot->delete()) {
			// delete picture
			if( $spot['Spot']['picture'] ) {
				$picturePath = $this->picturesPath . DS . $spot['Spot']['picture'];
				if( @file_exists($picturePath) ) {
					@unlink($picturePath);
				}
			}
			$this->setUserInfo( __("Spot deleted."), 'success' );
			$this->redirect(array('action' => 'index'));
		}
		
		$this->setUserInfo( __("Couldn't delete the Spot."), 'error' );
		$this->redirect(array('action' => 'index'));
	}
	
}